package flashcardtest;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import flashcardtest.FlashCardHand;
import flashcardtest.FlashCardSet;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class SetupServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// read data from form
		String setName = request.getParameter("set");
		String userName = request.getParameter("user");
		String mode = request.getParameter("mode");

		// reset message
		request.getSession().setAttribute("message", "");
		
		// forward immediately for options which require no special processing 
		if (mode.equals("New Dictionary")) {
			response.sendRedirect("/newdictionary.jsp");
			return;
		}
		else if (mode.equals("Upload Photo")) {
			response.sendRedirect("/upload.jsp");
			return;
		}
		else if (mode.equals("Album")) {
			response.sendRedirect("/album.jsp");
			return;
		}
		else if (mode.equals("User Data"))  {
			response.sendRedirect("/users.jsp");
			return;
		}

		// Return to main page for invalid mode
		if (!mode.equals("Start Quiz") && !mode.equals("Lookup") && 
				!mode.equals("Edit Dictionary") && !mode.equals("User Data")) {
			response.sendRedirect("/index.jsp");
			return;
		}
		
		// instantiate FlashCardSet
		FlashCardSet flashcardset;
		try {
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Query q = new Query("Dictionary");
			q.addFilter("name", Query.FilterOperator.EQUAL, setName);
			PreparedQuery pq = datastore.prepare(q);
			
			Entity dictionaryData = pq.asSingleEntity();
			String cat1 = (String) dictionaryData.getProperty("key1");
			String cat2 = (String) dictionaryData.getProperty("key2");
			flashcardset = new FlashCardSet(setName, cat1, cat2);
		}
		catch (PreparedQuery.TooManyResultsException e) {
			// there was not exactly 1 result of the query 
			flashcardset = new FlashCardSet("too many", "111","222");
		}
		catch (Exception e) {
			// some other unlikely problem
			flashcardset = new FlashCardSet("bad things");
		}
		// instantiate FlashCardHand
		FlashCardHand flashcardhand; 
		flashcardhand = new FlashCardHand(flashcardset);
				
		// save FlashCardHand and FlashCardSet to Session
		request.getSession().setAttribute("flashcardhand", flashcardhand);
		request.getSession().setAttribute("flashcardset", flashcardset);
	
		// redirect to correct page
		if (mode.equals("Lookup"))  {
			request.getSession().setAttribute("response1", "");
			request.getSession().setAttribute("response2", "");
			response.sendRedirect("/lookup.jsp");
			return;
		}
		else if (mode.equals("Edit Dictionary"))  {
			response.sendRedirect("/edit.jsp");
			return;
		}
		else if (mode.equals("Start Quiz"))  {
			
			// check for insufficient cards in deck
			if (flashcardset.size() < 3) {
				request.getSession().setAttribute("message", "There are not enough cards in this deck to start a quiz. Why don't you add a few?");
				response.sendRedirect("/edit.jsp");
				return;
			}
			
			// initialize test data
			request.getSession().setAttribute("testword", flashcardhand.getTestKey());
			request.getSession().setAttribute("word0", flashcardhand.getCardKey(0));
			request.getSession().setAttribute("word1", flashcardhand.getCardKey(1));
			request.getSession().setAttribute("word2", flashcardhand.getCardKey(2));
			
			request.getSession().setAttribute("correct", new Integer(0));
			request.getSession().setAttribute("incorrect", new Integer(0));
			request.getSession().setAttribute("result", "");
			//request.setAttribute("flashcardhand", flashcardhand);
			response.sendRedirect("/test.jsp");

			//RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/test.jsp");
			//dispatcher.forward(request,response);
			return;
		}

		// return to main page if there is no match
		response.sendRedirect("/index.jsp");
		return;
	
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user != null) {
			resp.setContentType("text/plain");
			resp.getWriter().println("Hello, " + user.getNickname());
		} else {
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
		
	
	}
	

}
